package com.gdust.gkyx.search.receiver;

import com.gdust.gkyx.mq.constant.MqConst;
import com.gdust.gkyx.search.service.SkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * ClassName: SkuReceiver
 * Package: com.gdust.gkyx.search.receiver
 * Description:监听商品上架与下架消息并执行相关操作
 *
 * @Author syun
 * @Create 2025/1/26 11:12
 * @Version 1.0
 */
@Component
public class SkuReceiver {
    /**
     * // 自动注入SkuService，用于处理商品上架与下架的业务逻辑
     */
    @Autowired
    private SkuService skuService;

    /**
     * 商品上架监听方法，监听RabbitMQ中的商品上架消息。
     *
     * @param skuId 商品ID
     * @param message RabbitMQ消息对象
     * @param channel RabbitMQ信道
     * @throws IOException 消息确认时可能抛出的IO异常
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER,durable = "true"),// 设置队列名称与持久化
            exchange = @Exchange(value = MqConst.EXCHANGE_GOODS_DIRECT),// 设置交换机
            key = {MqConst.ROUTING_GOODS_UPPER}// 设置路由键，确保与生产者的路由键匹配
    ))
    public void upperSku(Long skuId, Message message, Channel channel) throws IOException {
        if(skuId != null) {
            // 调用SkuService中的上架方法，执行商品上架操作
            skuService.upperSku(skuId);
        }
        // 确认消息已处理完毕，并从队列中删除
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    /**
     * 商品下架监听方法，监听RabbitMQ中的商品下架消息。
     *
     * @param skuId 商品ID
     * @param message RabbitMQ消息对象
     * @param channel RabbitMQ信道
     * @throws IOException 消息确认时可能抛出的IO异常
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER,durable = "true"),// 设置队列名称与持久化
            exchange = @Exchange(value = MqConst.EXCHANGE_GOODS_DIRECT),// 设置交换机
            key = {MqConst.ROUTING_GOODS_LOWER}// 设置路由键，确保与生产者的路由键匹配
    ))
    public void lowerSku(Long skuId, Message message, Channel channel) throws IOException {
        if(skuId != null) {
            // 调用SkuService中的下架方法，执行商品下架操作
            skuService.lowerSku(skuId);
        }
        // 确认消息已处理完毕，并从队列中删除
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}

